var errs = require('restify-errors')
var db = require('./mysql_service.js')
var rs = require('./redis_service')
var db = require('./mysql_service')
var validators = require('./validators.js')

// var fs = require('fs')
exports.get_list = function (args, res) {
  var stockCode = args.stock_code
  var pageIndex = args.page_index
  var pageSize = args.page_size
  if (!validators.isValidStockCodeA(stockCode)) {
    res.json(new errs.BadRequestError('非法的请求，请输入合法的{code}'))
  } else if (!validators.isValidPageIndex(pageIndex)) {
    res.json(new errs.BadRequestError('非法的请求，请输入合法的{pageIndex}'))
  } else if (!validators.isValidPageIndex(pageSize)) {
    res.json(new errs.BadRequestError('非法的请求，请输入合法的{pageSize}'))
  }else {
    let key = `list_${stockCode}_${pageIndex}_${pageSize}`
    let exists = false
    rs.get(key)
      .then(data => {
        if (data === null) {
          return db.getList(stockCode,pageIndex,pageSize)
        } else {
          exists = true
          return data
        }
      }).then(data => {
        if (!exists) {
          rs.set(key, data)
        }
        res.json(data)
      }).catch(e => {
        console.log(e)
        res.json(500, {
          code: e.name,
          message: e.message
        })
      })
  }
}

exports.get_file = function (args, res) {
  var fileName = args.name
  var date = args.date
  var type = args.type
  db.getFile(fileName,date,type).then(data => {
    res.json(data)
  }).catch(e => {
    res.json(500, {
      code: e.code,
      message: e.message
    })
  }) 
}